<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" class="tabs">
      <el-tab-pane label="基本信息" name="baseInfo">
        <el-row :gutter="20">
          <el-col :lg="24" :xs="24" class="mb-[12px]">
            <el-card style="min-width: 480px;margin-bottom: 18px;">
              <el-form
              ref="projectFormRef"
                :model="projectData"
                label-width="100px"
                disabled=true
              >
                <div class="form-flex">
                  <el-form-item label="项目名称" prop="projectName" class="form-item">
                    <el-input v-model="projectData.projectName" />
                  </el-form-item>
                </div>
                <div class="form-flex">
                  <el-form-item label="开发部门" prop="departmentName" class="form-item">
                    <el-input v-model="projectData.departmentName" />
                  </el-form-item>
                  <el-form-item label="项目经理" prop="projectManagerName" class="form-item">
                    <el-input v-model="projectData.projectManagerName" />
                  </el-form-item>
                </div>
                <div class="form-flex">
                  <el-form-item label="产品经理" prop="productManagerName" class="form-item">
                    <el-input v-model="projectData.productManagerName" />
                  </el-form-item>
                  <el-form-item label="实际启动时间" prop="beginDate" class="form-item">
                    <el-input v-model="projectData.beginDate" />
                  </el-form-item>
                </div>
                <div class="form-flex">
                  <el-form-item label="计划结束时间" prop="planEndDate" class="form-item">
                    <el-input v-model="projectData.planEndDate" />
                  </el-form-item>
                  <el-form-item label="实际结束时间" prop="endDate" class="form-item">
                    <el-input v-model="projectData.endDate" />
                  </el-form-item>
                </div>
                <div class="form-flex">
                  <el-form-item label="项目类型" prop="projectTypeText" class="form-item">
                    <el-input v-model="projectData.projectTypeText" />
                  </el-form-item>
                  <el-form-item class="form-item">
                  </el-form-item>
                </div>
                <el-form-item label="项目背景" prop="projectBackground">
                  <el-input v-model="projectData.projectBackground" :rows="4" type="textarea" />
                </el-form-item>
                <el-form-item label="项目目标" prop="projectTarget">
                  <el-input v-model="projectData.projectTarget" :rows="4" type="textarea" />
                </el-form-item>
                <el-form-item label="项目风险" prop="projectRisk">
                  <el-input v-model="projectData.projectRisk" :rows="4" type="textarea" />
                </el-form-item>
                <div class="form-flex">
                  <el-form-item label="创建人" prop="nickName">
                    <el-input v-model="projectData.nickName" />
                  </el-form-item>
                  <el-form-item label="创建时间" prop="createTime">
                    <el-input v-model="projectData.createTime" />
                  </el-form-item>
                </div>
                <div class="form-flex">
                  <el-form-item label="附件" prop="attachments">
                    <span v-for="(attachment, index) in fileList">
                      <p style="padding-left: 10px;"><a :href="attachment.url" target="_blank" style="text-decoration:underline;">{{ attachment.name }}</a></p>
                    </span>
                  </el-form-item>
                </div>
              </el-form>
            </el-card>
    
            <el-collapse v-model="activeNames">
              <el-collapse-item title="项目里程碑" name="1" style="margin-bottom: 18px;">
                <el-table
                  :data="milestoneTableData"
                  border
                  style="margin:10px"
                >
                  <el-table-column label="序号" width="70" align="center">
                    <template #default="{ $index }">
                      {{ $index + 1 }}
                    </template>
                  </el-table-column>
                  <el-table-column label="里程碑" prop="milestoneName" width="180" align="center">
                  </el-table-column>
                  <el-table-column label="任务" prop="milestoneTask" width="250" align="center">
                  </el-table-column>
                  <el-table-column label="计划完成时间" prop="milestoneDate" width="250" align="center">
                  </el-table-column>
                </el-table>
              </el-collapse-item>
    
              <el-collapse-item title="项目组成员" name="2" style="margin-bottom: 18px;">
                <el-table
                  :data="memberTableData"
                  border
                  style="margin:10px"
                >
                  <el-table-column label="序号" width="70" align="center">
                    <template #default="{ $index }">
                      {{ $index + 1 }}
                    </template>
                  </el-table-column>
                  <el-table-column label="角色" prop="memberType" width="180" align="center">
                  </el-table-column>
                  <el-table-column label="项目组成员" prop="users" width="250" align="center">
                  </el-table-column>
                </el-table>
              </el-collapse-item>
    
              <el-collapse-item title="关联需求" name="3"  style="margin-bottom: 18px;">
                <el-table
                  ref="requirementTableRef"
                  :data="requirementList"
                  highlight-current-row
                  border
                >
                  <el-table-column label="需求编码" prop="code" min-width="150" />
                  <el-table-column label="需求标题" prop="title" min-width="250" />
                  <el-table-column label="创建人" prop="nickName" width="120" />
                  <el-table-column label="创建时间" prop="createTime" width="180" />
                  <el-table-column label="创建部门" prop="departmentName" width="150" />
                  <el-table-column label="附件" prop="attachments" width="250">
                    <template #default="{ row }">
                      <span v-for="(attachment, index) in handleAttachments(row.attachments)" :key="index">
                        <p><a :href="attachment.url" target="_blank" style="text-decoration:underline;">{{ attachment.name }}</a></p>
                      </span>
                    </template>
                  </el-table-column>
                </el-table>
              </el-collapse-item>
            </el-collapse>
    
            <el-card style="min-width: 480px;margin-bottom: 18px;" v-for="(examine, index) in examineList">
              <el-form
                label-width="100px"
                disabled=true
              >
                <el-form-item label="审批意见" prop="examineStatus">
                  <el-input :value="examine.examineStatus == 1 ? '通过' : '驳回'" />
                </el-form-item>
    
                <el-form-item label="意见明细" prop="content">
                  <el-input :value="examine.content" />
                </el-form-item>
    
                <el-form-item label="审批人" prop="nickName">
                  <el-input v-model="examine.nickName" />
                </el-form-item>
    
                <el-form-item label="审批时间" prop="createTime">
                  <el-input v-model="examine.createTime" />
                </el-form-item>
              </el-form>
            </el-card>
    
            <flowHistory :flowId="route.query.flowId" :workId="route.query.workId" />
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="项目计划" name="projectPlan">
        <el-card shadow="never" class="table-container">
          <template #header>
            <el-button
              type="primary"
              :disabled="disabledButton"
              @click="handleSavePlan()"
            >
              保存</el-button
            >
            <el-button
              type="success"
              :disabled="disabledButton"
              @click="handleAddTask()"
            >
              新增任务</el-button
            >
            <el-button
              type="warning"
              :disabled="disabledButton"
              @click="handleDeleteTask()"
            >
              删除任务</el-button
            >
          </template>
    
          <el-table
            ref="planTableRef"
            v-loading="loading"
            :data="planTableData"
            highlight-current-row
            row-key="id"
            default-expand-all=true
            @selection-change="handleSelectionChange"
            @row-click="handleRowClick"
            :tree-props="{
              children: 'children',
              hasChildren: 'hasChildren',
              label: 'status'
            }"
            :header-cell-class-name="mustAdd"
          >
            <el-table-column type="selection" width="55" :selectable='selectEnable' />
            <el-table-column label="任务名称" min-width="250">
              <template #default="scope">
                <span v-if="currentSelectRow !== scope.row" style="width: 100%;">{{ scope.row.taskName }}</span>
                <el-input v-else v-model="scope.row.taskName" style="width:190px;" :disabled="scope.row.status > 1 || disabledButton" />
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag v-if="scope.row.status === 1" type="primary"
                  >未开始</el-tag
                >
                <el-tag v-if="scope.row.status === 2" type="warning"
                  >进行中</el-tag
                >
                <el-tag v-if="scope.row.status === 3" type="success"
                  >发布</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column label="查看" align="center" width="80">
              <template #default="scope">
                <el-button
                  type="primary"
                  link
                  size="default"
                  @click.stop="handleViewPlan(scope.row)"
                  v-if="scope.row.parentId != -1"
                >
                <el-icon><View /></el-icon>
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="责任人" width="150">
              <template #default="scope">
                <span v-if="currentSelectRow !== scope.row" style="width: 100%;">{{ scope.row.nickName }}</span>
                <el-select v-model="scope.row.userId" filterable v-else :disabled="scope.row.status > 1 || disabledButton"
                  @change="handleUserChange(scope.row)">
                  <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :value="item.userId"
                  :label="item.nickName"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="计划开始时间" width="250">
              <template #default="scope">
                <span v-if="currentSelectRow !== scope.row" style="width: 100%;">{{ scope.row.beginDate }}</span>
                <el-date-picker v-model="scope.row.beginDate" type="date" v-else value-format="YYYY-MM-DD" :disabled="scope.row.status > 1 || disabledButton" />
              </template>
            </el-table-column>
            <el-table-column label="计划完成时间" min-width="250">
              <template #default="scope">
                <span v-if="currentSelectRow !== scope.row" style="width: 100%;">{{ scope.row.endDate }}</span>
                <el-date-picker v-model="scope.row.endDate" type="date" v-else value-format="YYYY-MM-DD" :disabled="scope.row.status > 1 || disabledButton" />
              </template>
            </el-table-column>
            <el-table-column fixed="right" align="center" label="操作" width="100">
              <template #default="scope">
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click.stop="handleDeal(scope.row)"
                  v-if="scope.row.id != null && scope.row.userId === currentUserId"
                >
                  <i-ep-plus />处理
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <!-- 任务处理弹窗 -->
        <el-dialog
          v-model="dealVisible"
          title="任务处理"
          width="650px"
          @close="handleCloseDialog"
        >
        <el-form
          ref="dealFormRef"
          :model="dealFormData"
          :rules="dealFormRules"
          :disabled="dealFormDisabled"
          label-width="120px"
        >
          <div class="form-flex">
            <el-form-item label="任务名称" prop="taskName" class="form-item">
              <el-input v-model="dealFormData.taskName" disabled="true" />
            </el-form-item>
          </div>
          <div class="form-flex">
            <el-form-item label="实际完成时间" prop="realEndDate" class="form-item">
              <el-date-picker
                  v-model="dealFormData.realEndDate"
                  type="date"
                  style="width:184px"
                />
            </el-form-item>
            <el-form-item label="完成率%" prop="completionRate" class="form-item">
              <el-input v-model="dealFormData.completionRate" />
            </el-form-item>
          </div>
          <div class="form-flex">
            <el-form-item label="描述" prop="remark" class="form-item">
              <el-input v-model="dealFormData.remark" :rows="3" type="textarea" />
            </el-form-item>
          </div>
          <div class="form-flex">
            <el-form-item label="延期原因" prop="delayReason" class="form-item">
              <el-input v-model="dealFormData.delayReason" :rows="3" type="textarea" />
            </el-form-item>
          </div>
          <div class="form-flex">
            <el-form-item label="计划开始时间" prop="beginDate" class="form-item">
              <el-date-picker
                  v-model="dealFormData.beginDate"
                  type="date"
                  style="width:184px"
                  disabled="true"
                />
            </el-form-item>
            <el-form-item label="计划完成时间" prop="endDate" class="form-item">
              <el-date-picker
                  v-model="dealFormData.endDate"
                  type="date"
                  style="width:184px"
                  disabled="true"
                />
            </el-form-item>
          </div>
          <div class="form-flex">
            <el-form-item label="附件" prop="attachments" class="form-item">
              <el-upload
                v-model:file-list="dealFileList"
                class="upload-demo"
                action="/api/bus/upload/uploadFiles"
                multiple
                :on-remove="handleRemove"
                :limit="5"
                :on-success="handleFileSuccess"
                :before-upload="beforeFileUpload"
                :on-preview="handleFilePreview"
              >
                <el-button type="primary">上传附件</el-button>

              </el-upload>
            </el-form-item>
          </div>
        </el-form>

          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="handleSubmit">确 定</el-button>
              <el-button @click="handleCloseDialog">取 消</el-button>
            </div>
          </template>
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="项目问题" name="projectProblem">
        <div class="search-container">
          <el-form ref="queryProblemFormRef" :model="queryProblemParams" :inline="true">
            <el-form-item prop="title" label="问题标题">
              <el-input
                v-model="queryProblemParams.title"
                placeholder="问题标题"
                clearable
              />
            </el-form-item>

            <el-form-item prop="rangeTime" label="提出时间">
              <el-date-picker
                v-model="rangeTime"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                @change="handleRangeTimeChange"
                value-format="YYYY-MM-DD HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
    
            <el-form-item>
              <el-button type="primary" @click="handleQueryProblem"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="handleResetQueryProblem"><i-ep-refresh />重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never" class="table-container">
          <template #header>
            <el-button type="success" @click="handleAddProblem()"
              ><i-ep-plus />创建问题</el-button
            >
          </template>
    
          <el-table
            v-loading="loading"
            :data="problemTableData"
            highlight-current-row
            border
          >
            <el-table-column label="问题标题" prop="title" min-width="250">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="default"
                  link
                  @click="showProblemDetails(scope.row.id)"
                >
                  {{scope.row.title}}
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="问题等级" prop="level" width="120">
              <template #default="scope">
                <el-tag v-if="scope.row.level === 1" type="danger"
                  >致命</el-tag
                >
                <el-tag v-if="scope.row.level === 2" type="warning"
                  >严重</el-tag
                >
                <el-tag v-if="scope.row.level === 3" type="primary"
                  >一般</el-tag
                >
                <el-tag v-if="scope.row.level === 4" type="info"
                  >提示</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column label="问题描述" prop="description" width="250" show-overflow-tooltip>
              <template #default="scope">
                <div v-html="scope.row.description" style="width:250px;height:25px"></div>
              </template>
            </el-table-column>
            <el-table-column label="问题状态" prop="status" width="120" >
              <template #default="scope">
                <el-tag v-if="scope.row.status === 1" type="primary"
                  >编制中</el-tag
                >
                <el-tag v-if="scope.row.status === 2" type="danger"
                  >未解决</el-tag
                >
                <el-tag v-if="scope.row.status === 3" type="primary"
                  >已解决</el-tag
                >
                <el-tag v-if="scope.row.status === 4" type="success"
                  >已关闭</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column label="提出人" prop="creatorName" width="100" />
            <el-table-column label="提出时间" prop="createTime" width="180" />
            <el-table-column label="解决人" prop="resolveName" width="100" />
            <el-table-column label="解决时间" prop="resolveTime" width="180" />
            <el-table-column fixed="right" label="操作" width="120">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  link
                  v-show="scope.row.creator === currentUserId && scope.row.status === 1"
                  @click="handleProblemEdit(scope.row.id)"
                >
                  <i-ep-edit />编辑
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="problemTotal > 0"
            v-model:total="problemTotal"
            v-model:page="queryProblemParams.page"
            v-model:limit="queryProblemParams.size"
            @pagination="handleQueryProblem"
          />
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ProjectDetails",
  inheritAttrs: false,
});

import flowHistory from '../../work/backlog/components/flowHistory.vue';
import ProjectAPI, { ProjectData, ProjectPlan, ProjectProblemPageVO, ProjectProblemPageQuery } from "@/api/project";
import ExamineAPI, { ExamineData, ExamineDataVO } from "@/api/examine";
import router from "@/router";
import WorkAPI from "@/api/work";
import UserAPI from "@/api/user";

const route = useRoute();

// 基本信息
const activeTab = ref('baseInfo');
const projectFormRef = ref(ElForm);
// 项目表单
const projectData = reactive<ProjectData>({});
const fileList = ref<UploadUserFile[]>([])
// 面板收缩
const activeNames = ref(['1', '2', '3']);
// 里程碑-列表数据
const milestoneTableData = ref([]);
// 项目组成员-列表数据
const memberTableData = ref([]);
// 关联需求
const requirementTableRef = ref();
const requirementList = ref([]);
const examineList = ref<ExamineDataVO[]>([]);

// 项目计划相关
const planTableRef = ref();
// 计划表格数据
const planTableData = ref<ProjectPlan[]>([]);
const loading = ref(false);
// 表格标题增加红色星号
const mustAdd = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex == 1 || columnIndex == 3 || columnIndex == 4 || columnIndex == 5) {
    return 'must';
  }
}
// 查询计划
function handleQueryPlan() {
  loading.value = true;
  ProjectAPI.getPlanTree(projectData.id)
    .then(({data}) => {
      planTableData.value = data;
    })
    .finally(() => {
      loading.value = false;
    });
}
function selectEnable(row, rowIndex) {
  if (row.parentId == -1) {
    return false //禁用
  } else {
    return true//不禁用
  }
}
let currentSelectRow = null;
function handleRowClick(row: any) {
  currentSelectRow = row;
}
function handleAddTask(){
  const plan : ProjectPlan = {};
  if (currentSelectRow != null){
    if (currentSelectRow.parentId == -1){
      plan.parentId = currentSelectRow.id;
      currentSelectRow.children.push(plan);
      currentSelectRow = currentSelectRow.children[currentSelectRow.children.length - 1]
    }
    else{
      let parent = planTableData.value.find(s => s.id == currentSelectRow.parentId);
      if (parent){
        plan.parentId = parent.id;
        let index = parent.children.indexOf(currentSelectRow);
        parent.children.splice(index + 1, 0, plan);
        currentSelectRow = parent.children[index + 1];
      }
    }
  }
  else{
    if (planTableData.value.length > 0){
      plan.parentId = planTableData.value[planTableData.value.length - 1].id;
      planTableData.value[planTableData.value.length - 1].children.push(plan);
      currentSelectRow = planTableData.value[planTableData.value.length - 1].children[planTableData.value[planTableData.value.length - 1].children.length - 1];
    }
  }
}
const checkedRows = ref([]); // 存储勾选的行数据
const handleSelectionChange = (selection) => {
  checkedRows.value = selection; // 更新选中的行数据
};
function handleDeleteTask(){
  for(let i = 0; i < checkedRows.value.length; i++){
    let row = checkedRows.value[i];
    if (row.parentId != -1){
      let parent = planTableData.value.find(s => s.id == row.parentId);
      if (parent){
        let index = parent.children.indexOf(row);
        parent.children.splice(index, 1);
      }
    }
  }
}
// 人员选择框
const userList = ref([]);
function handleSavePlan(){
  let projectId = projectData.id;
  let plans = planTableData.value;
  for (let i = 0; i < plans.length; i++){
    let plan = plans[i];
    if (plan.beginDate == null || plan.endDate == null){
      ElMessage.warning("必填项不能为空");
      return;
    }
    if (plan.children){
      for(let j = 0; j < plan.children.length; j++){
        let childPlan = plan.children[j];
        if (childPlan.taskName == null || childPlan.userId == null || childPlan.beginDate == null || childPlan.endDate == null){
          ElMessage.warning("必填项不能为空");
          return;
        }
      }
    }
  }
  ProjectAPI.saveProjectPlan(projectId, plans)
    .then(({data}) => {
      ElMessage.success("保存成功");
      currentSelectRow = null;
    })
    .finally(() => (loading.value = false));
}

function handleUserChange(row){
  row.nickName = userList.value.find(s => s.userId == row.userId).nickName;
}

// 按钮权限
const currentUserId = parseInt(sessionStorage.getItem('userId'));
const disabledButton = ref(true);

// 任务处理相关
const dealVisible = ref(false);
const dealFormRef = ref(ElForm);
const dealFormDisabled = ref(false);
const dealFormData = reactive<ProjectPlan>({});
const dealFormRules = reactive({
  realEndDate: [{ required: true, message: "请输入实际完成时间", trigger: "blur" }],
  completionRate: [{ required: true, message: "请输入完成率", trigger: "blur" }],
  remark: [{ required: true, message: "请输入描述", trigger: "blur" },{ min: 1, max: 100, message: '输入长度在 1 到 100 个字符', trigger: 'blur' }],
  delayReason: [{ min: 1, max: 100, message: '输入长度在 1 到 100 个字符', trigger: 'blur' }],
});
function handleDeal(row){
  dealFormData.id = row.id;
  dealFormData.taskName = row.taskName;
  dealFormData.completionRate = row.completionRate;
  dealFormData.realEndDate = row.realEndDate;
  dealFormData.remark = row.remark;
  dealFormData.delayReason = row.delayReason;
  dealFormData.beginDate = row.beginDate;
  dealFormData.endDate = row.endDate;
  dealFormData.attachments = row.attachments;
  dealFileList.value = [];
  if (dealFormData.attachments){
    let files = JSON.parse(dealFormData.attachments);
    for(let i = 0; i < files.length; i++){
      dealFileList.value.push({name: files[i]["name"], url: files[i]["url"]});
    }
  }
  dealVisible.value = true;
  dealFormDisabled.value = false;
}
function handleCloseDialog(){
  dealVisible.value = false;
}
const dealFileList = ref<UploadUserFile[]>([])
const handleFileSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  formData.attachments = response.data
}
const beforeFileUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 50) {
    ElMessage.error('文件大小不能超过50MB!')
    return false
  }
  return true
}
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  // console.log(file, uploadFiles)
}
const handleSubmit = () => {
    // 处理附件
    let files = [];
    for(let i = 0; i < dealFileList.value.length; i++){
      if (dealFileList.value[i].response){
        files.push(dealFileList.value[i].response.data[0])
      }
      else{
        let fileJson = {};
        fileJson.name = dealFileList.value[i].name;
        fileJson.url = dealFileList.value[i].url;
        files.push(fileJson);
      }
    }
    dealFormData.attachments = JSON.stringify(files);
    loading.value = true;
    ProjectAPI.dealProjectPlan(dealFormData)
        .then((data) => {
          ElMessage.success(data.msg);
          dealVisible.value = false;
          handleQueryPlan()
        })
        .finally(() => (loading.value = false));
}
function handleViewPlan(row){
  dealFormData.id = row.id;
  dealFormData.taskName = row.taskName;
  dealFormData.completionRate = row.completionRate;
  dealFormData.realEndDate = row.realEndDate;
  dealFormData.remark = row.remark;
  dealFormData.delayReason = row.delayReason;
  dealFormData.beginDate = row.beginDate;
  dealFormData.endDate = row.endDate;
  dealFormData.attachments = row.attachments;
  if (dealFormData.attachments){
    let files = JSON.parse(dealFormData.attachments);
    for(let i = 0; i < files.length; i++){
      dealFileList.value.push({name: files[i]["name"], url: files[i]["url"]});
    }
  }
  dealVisible.value = true;
  dealFormDisabled.value = true;
}

// 项目问题相关
const problemTableData = ref<ProjectProblemPageVO[]>([]);
const queryProblemFormRef = ref(ElForm);
const problemTotal = ref(0);
const queryProblemParams = reactive<ProjectProblemPageQuery>({
  page: 1,
  size: 10,
});
// 查询问题
function handleQueryProblem() {
  loading.value = true;
  queryProblemParams.projectId = projectData.id;
  ProjectAPI.getProblemPage(queryProblemParams)
    .then(({data}) => {
      problemTableData.value = data.list;
      problemTotal.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
// 重置查询问题
function handleResetQueryProblem() {
  queryProblemFormRef.value.resetFields();
  queryProblemParams.title = '';
  queryProblemParams.beginTime = '';
  queryProblemParams.endTime = '';
  queryProblemParams.page = 1;
  handleQueryProblem();
}
const rangeTime = ref("");
function handleRangeTimeChange(){
  queryProblemParams.beginTime = rangeTime.value[0];
  queryProblemParams.endTime = rangeTime.value[1];
}
function handleAddProblem(){
  router.push({ path: '/projectList/problemApply', query: { projectId: projectData.id } });
}
function handleProblemEdit(id: number) {
  router.push({ path: '/projectList/problemApply', query: { id: id, projectId: projectData.id }});
}
function showProblemDetails(id: number) {
  WorkAPI.getProcessByFormDataId(id, "bus_project_problem").then(({data}) => {
    if (data){
      router.push({ path: '/projectList/problemDetails', query: { workId: data.workId, processId: data.processId, 
        flowId: data.flowId, nodeName: data.nodeName }});
    }
    else{
      router.push({ path: '/projectList/problemDetails', query: { id: id }});
    }
  })
}

onMounted(() => {
  if (route.query.workId){
    ProjectAPI.getByWorkId(route.query.workId).then(({data}) => {
      if (data){
        projectData.id = data.id;
        projectData.projectCode = data.projectCode;
        projectData.projectName = data.projectName;
        projectData.projectManager = data.projectManager;
        projectData.projectManagerName = data.projectManagerName;
        projectData.productManagerName = data.productManagerName;
        projectData.departmentId = data.departmentId;
        projectData.departmentName = data.departmentName;
        projectData.beginDate = data.beginDate;
        projectData.endDate = data.endDate;
        projectData.planEndDate = data.planEndDate;
        projectData.projectType = data.projectType;
        projectData.projectBackground = data.projectBackground;
        projectData.projectTarget = data.projectTarget;
        projectData.projectRisk = data.projectRisk;
        projectData.nickName = data.nickName;
        projectData.createTime = data.createTime;
        projectData.attachments = data.attachments;
        switch(data.projectType){
          case 1:
            projectData.projectTypeText = "N类全新项目";
          break;
          case 2:
            projectData.projectTypeText = "A类改进项目";
          break;
          case 3:
            projectData.projectTypeText = "B类改进项目";
          break;
          case 4:
            projectData.projectTypeText = "R类预研项目";
          break;
          default:
          break;
        }
        if (projectData.attachments){
          let files = JSON.parse(projectData.attachments);
          for(let i = 0; i < files.length; i++){
            fileList.value.push({name: files[i]["name"], url: files[i]["url"]});
          }
        }
        if (data.milestones){
          milestoneTableData.value = data.milestones;
        }
        if (data.members){
          for (let i = 0; i < data.members.length; i++){
            let member = data.members[i];
            let isExist = false;
            for (let j = 0; j < memberTableData.value.length; j++){
              let data = memberTableData.value[j];
              if (data.memberType == member.memberType){
                isExist = true;
                data.users += ",  " + member.nickName;
              }
            }
            if (!isExist){
              memberTableData.value.push({ "memberType": member.memberType, "users": member.nickName })
            }
          }
        }
        if (data.requirementList){
          requirementList.value = data.requirementList;
        }
        // 按钮权限
        disabledButton.value = projectData.projectManager !== currentUserId && data.creator !== currentUserId;

        // 获取项目计划
        handleQueryPlan();
        // 获取项目问题
        handleQueryProblem();
      }
    })

    ExamineAPI.getByWorkId(route.query.workId).then(({data}) => {
      if (data){
        for(let i = 0; i < data.length; i++){
          let examine = reactive<ExamineDataVO>({ });
          examine.id = data[i].id;
          examine.examineStatus = data[i].examineStatus;
          examine.content = data[i].content;
          examine.nickName = data[i].nickName;
          examine.createTime = data[i].createTime;
          examineList.value.push(examine);
        }
      }
    })
  }

  // 获取用户列表
  UserAPI.getUserList()
    .then(({data}) => {
      userList.value = data;
  })
});

function handleAttachments(attachments){
  if (attachments){
    return JSON.parse(attachments);
  }
  else{
    return [];
  }
}

function handleFilePreview(file) {
  const fileUrl = file.url
  const a = document.createElement('a')
  a.href = fileUrl
  a.download = file.name
  a.style.display = 'none'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

</script>

<style type="text/css">
  .form-flex {
    display: flex;
    gap: 10px; /* 间距 */
    margin-bottom: 18px;
  }
  .form-item {
    flex: 1; /* 使所有表单项平均分配空间 */
    margin: 0; /* 移除默认的 margin */
  }
  .el-collapse-item__header{
    padding-left: 10px;
    font-size: 14px;
    font-weight: bold;
  }
  table th.must div:before{ 
	  content: '*';
	  color: red !important; 
	}
</style>
